package cn.varin.mqttclientapi.config;

import cn.varin.mqttclientapi.entity.MqttConfigProperties;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

@Configuration
public class MqttConfig {
    // yml获取配置内容
    @Autowired
    private MqttConfigProperties mqttConfigProperties;
//    连接工厂建立
    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory (){
        // 建立默认工程
        DefaultMqttPahoClientFactory defaultMqttPahoClientFactory = new DefaultMqttPahoClientFactory();
        // 设置连接选项内容
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setUserName(mqttConfigProperties.getUsername());
        mqttConnectOptions.setPassword(mqttConfigProperties.getPassword().toCharArray());
        mqttConnectOptions.setServerURIs(new String[]{mqttConfigProperties.getUrl()});

        defaultMqttPahoClientFactory.setConnectionOptions(mqttConnectOptions );
        return  defaultMqttPahoClientFactory;
    }
}
